package com.study.demo_file_upload.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName: FileUpLoad
 * @Description:
 * @author: WS
 * @date 2020/12/10
 * @Version: 1.0
 **/
@RestController
public class FileUpLoadController {
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("/yyyy/MM/dd/");
    @PostMapping("/fileupload")
    public String upload(MultipartFile file, HttpServletRequest request){
        String format = simpleDateFormat.format(new Date());
        String realPath = request.getServletContext().getRealPath("/img")+ format;
        File folder = new File(realPath);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        String newFileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            file.transferTo(new File(realPath,newFileName));
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/img" + format + newFileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }
    @PostMapping("/fileuploads")
    public String uploads(MultipartFile[] files, HttpServletRequest request){
        String format = simpleDateFormat.format(new Date());
        String realPath = request.getServletContext().getRealPath("/img")+ format;
        File folder = new File(realPath);
        if(!folder.exists()){
            folder.mkdirs();
        }
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
            String newFileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
            try {
                file.transferTo(new File(realPath,newFileName));
                String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/img" + format + newFileName;
                System.out.println(url);
            } catch (IOException e) {
                e.printStackTrace();
                return "error";
            }
        }
        return "success";
    }
}
